import { app, shell, BrowserWindow, ipcMain, globalShortcut ,Tray} from 'electron'
const { join } = require('path')
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import icon2 from '../../resources/icon2.png?asset'
import { logger, dbManager, cmdExecutor  }  from './CommonUtils.js';


let tray = null;

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: true,
    autoHideMenuBar: false,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      // sandbox: false
      devTools: true
    }
  })

  globalShortcut.register('F12', () => {
    mainWindow.webContents.toggleDevTools();
  });

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  //设置图标
  if(process.platform === 'darwin' ){
      app.dock.setIcon(icon)
  }

  // mainWindow.webContents.toggleDevTools();

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => logger.info('pong'))


  // 初始化DB
  // initDB();

  //IPCMain监听的方法
  mainOn();


  //设置自启动
  ipcMain.handle('enableWhenLogin', (envent, enable) => {
    app.setLoginItemSettings({
      openAtLogin: enable,
      openAsHidden: false,
      enabled: true
    })
    return app.getLoginItemSettings();
  })

  //创建窗口
  createWindow()

  tray = new Tray(icon2)

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})



function mainOn() {

  // 监听cmdconfig表的事件
  mainOnConfigDB();

  //监听日志文件事件
  mainOneLog();

  //监听ps aux 命令事件
  mainPsAuxSheel()

  //执行脚本
  mainDoCmdJob();

}

/**
 * 执行存储的脚本
 */
function mainDoCmdJob() {

  //先读取存储的sql  查询这个表 cmd_table  然后获取命令，拼接之后执行
  dbManager.query("select * from cmd_table;").then((rows) => {
    rows.forEach((row) => {
      logger.info(JSON.stringify(row));
      cmdExecutor.execShellCommand(row.cmd + " " + row.param)
      .then(()=>{
        logger.info("执行完成");
      })
      .catch((err)=>{
        logger.info("执行失败" + err.message);
      });
    });
  });

}


function mainPsAuxSheel() {
  ipcMain.handle('ps:all', async (event, params) => {
    return await cmdExecutor.execShellCommand('ps aux');
  })
}


function mainOneLog() {
  //监听tail命令的文件
  ipcMain.handle('syslog', async (event, params) => {
    let lines = await logger.getLastLines(30);
    return lines;
  })
}



function mainOnConfigDB() {
  ipcMain.handle('dbCmdConfig', (envent, sql_string) => {

    var splitIndex = sql_string.indexOf(":");
    var part1 = sql_string.substring(0, splitIndex);
    var part2 = sql_string.substring(splitIndex + 1);

    let res = null;
    if (part1 === 'query') {
      res = (async () => {
        try {
          // 执行查询
          const rows = await dbManager.query(part2);
          return rows;
        } catch (err) {
          logger.info(err.message);
        }
      })();
    } else if (part1 === 'add') {
      res = (async () => {
        try {
          const rows = await dbManager.insert(part2);
          return rows;
        } catch (err) {
          logger.info(err.message);
        }
      })();
    } else if (part1 === 'delete') {
      res = (async () => {
        try {
          const rows = await dbManager.delete(part2);
          return rows;
        } catch (err) {
          logger.info(err.message);
        }
      })();
    } else if (part1 === 'edit') {
      res = (async () => {
        try {
          const rows = await dbManager.update(part2);
          return rows;
        } catch (err) {
          logger.info(err.message);
        }
      })();
    }

    logger.info("db返回的对象:" + res);
    return res;
  });


  ipcMain.handle('execTable', (envent, sql_string) => {

    var splitIndex = sql_string.indexOf(":");
    var part1 = sql_string.substring(0, splitIndex);
    var part2 = sql_string.substring(splitIndex + 1);

    let res = null;
    if (part1 === 'query') {
      res = (async () => {
        try {
          // 执行查询
          const rows = await dbManager.query(part2);
          return rows;
        } catch (err) {
          logger.info(err.message);
        }
      })();
    } else if (part1 === 'delete') {
      res = (async () => {
        try {
          const rows = await dbManager.delete(part2);
          return rows;
        } catch (err) {
          logger.info(err.message);
        }
      })();
    } 
    
    logger.info("db返回的对象:" + res);
    return res;
  });


}
// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
